package com.jy.appmarket.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import com.jy.app.market.idata.card.CardApkRecommend;
import com.jy.app.market.idata.card.CardWords;
import com.jy.appmarket.AppMarketApplication;
import com.jy.appmarket.R;
import com.jy.appmarket.cards.ApkRecommendUICard;
import com.jy.appmarket.cards.HotWordsUICard;
import com.jy.appmarket.download.DownloadActivity;
import com.jy.appmarket.network.engine.BaseNetEngine;
import com.jy.appmarket.network.engine.HotWordsNetEngine;
import com.jy.appmarket.network.resultdata.HotWordsResultData;
import com.jy.appmarket.network.task.NetTask;
import com.jy.appmarket.network.task.NetTask.NetTaskListener;
import com.jy.appmarket.statistics.ApkSource;
import com.jy.appmarket.statistics.umeng.myUmengStaticstics;
import com.jy.appmarket.utils.ActivateStatistics;
import com.jy.appmarket.utils.ApkRecommendHolder;
import com.jy.appmarket.utils.ApkRecommendHolder.ApkRecommendUpdateListener;
import com.rad.statistics.android.StatisticsAgent;
import com.umeng.analytics.MobclickAgent;

import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
import it.gmariotti.cardslib.library.internal.Card;
import it.gmariotti.cardslib.library.internal.Card.OnCardClickListener;
import it.gmariotti.cardslib.library.internal.CardGridArrayAdapter;
import it.gmariotti.cardslib.library.view.CardGridView;
import it.gmariotti.cardslib.library.view.CardView;

public class SearchActivity extends DownloadActivity implements NetTaskListener, OnCardClickListener,
		OnEditorActionListener, View.OnClickListener, ApkRecommendUpdateListener {

	public static final String EXTRA_NAME = "app_detail_name";
	public static final String EXTRA_PKG = "app_detail_package";
	private NetTask mNetTask;
	private CardGridView mGridview;
	private CardGridArrayAdapter mCardAdapter;
	private ArrayList<Card> mCardsArray = new ArrayList<Card>();

	private EditText mSearchEt;
	private ImageView mClearEditView;
	private CardApkRecommend mRecommend;
	private Handler mHandler = new Handler();
	private List<String> mWords;
	private boolean mDestroyed = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search);
		initTitle();
		initGridView();
		loadData();
		Intent intent = getIntent();
		if ("android.intent.action.MAIN".equals(intent.getAction())) {
			StatisticsAgent.onEvent(getApplicationContext(), "clickSearchShortCut");
			myUmengStaticstics.clickSearchShortCut(getApplicationContext());
		}

		mHandler.postDelayed(initTask, 200);
		mDestroyed = false;
		ActivateStatistics.ActivateFrom(this, this.getClass().getSimpleName());
	}

	private Runnable initTask = new Runnable() {
		@Override
		public void run() {
			initRecommend();
		}
	};

	private void initRecommend() {
		mRecommend = ApkRecommendHolder.getInstance().getRecommend();
		final CardView recommendView = findViewById(R.id.search_recommend_card);
		if (mRecommend == null) {
			recommendView.setVisibility(View.GONE);
			ApkRecommendHolder.getInstance().updateRecommend(getApplicationContext(), this);
		} else {
			recommendView.setVisibility(View.VISIBLE);
			mRecommend.setTitle("大家还搜索了");
			ApkRecommendUICard recommendCard = new ApkRecommendUICard(this, mRecommend);
			recommendCard.setApkSource(new ApkSource("recommend", null, null, "search"));
			recommendView.setCard(recommendCard);
			addFileListener(recommendCard);
		}
	}

	private void initTitle() {
		ActionBar actionBar = getActionBar();
		actionBar.setDisplayShowTitleEnabled(false);
		actionBar.setDisplayUseLogoEnabled(false);
		actionBar.setDisplayShowHomeEnabled(false);
		actionBar.setDisplayHomeAsUpEnabled(false);
		actionBar.setDisplayShowCustomEnabled(true);
		actionBar.setHomeButtonEnabled(false);

		actionBar.setCustomView(R.layout.cust_search_view);
		findViewById(R.id.back_bn).setOnClickListener(this);
		mClearEditView = findViewById(R.id.clear_edit_view);
		mClearEditView.setOnClickListener(this);
		mSearchEt = findViewById(R.id.search_ev);
		mSearchEt.setOnEditorActionListener(this);
		mSearchEt.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				if (count > 0) {
					mClearEditView.setVisibility(View.VISIBLE);
				} else {
					mClearEditView.setVisibility(View.GONE);
				}
			}

			@Override
			public void afterTextChanged(Editable s) {
				if (s.length() > 0) {
					mClearEditView.setVisibility(View.VISIBLE);
				} else {
					mClearEditView.setVisibility(View.GONE);
				}
			}
		});
	}

	private void initGridView() {
		mGridview = findViewById(R.id.hot_words_cardgridview);
		mCardAdapter = new CardGridArrayAdapter(this, mCardsArray);
		mGridview.setAdapter(mCardAdapter);
	}

	private void loadData() {
		HotWordsNetEngine engine = new HotWordsNetEngine();
		mNetTask = new NetTask(this, engine, 1);
		mNetTask.setListener(this);
		new Thread(mNetTask).start();
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	protected void onDestroy() {
		mHandler.removeCallbacks(initTask);
		mDestroyed = true;
		if (mNetTask != null) {
			mNetTask.cancel();
			mNetTask.setListener(null);
			mNetTask = null;
		}
		super.onDestroy();
	}

	@Override
	public void onTaskRunSuccessful(int tag, BaseNetEngine engine) {

		HotWordsResultData resultData = (HotWordsResultData) engine.getResultData();
		if (resultData.isOK()) {
			CardWords cardWords = resultData.getCardWords();
			if (cardWords == null) {
				return;
			}
			List<String> words = cardWords.getWords();
			if (cardWords == null || words.size() == 0) {
				return;
			}
			mWords = words;

			findViewById(R.id.hot_word_title_layout).setVisibility(View.VISIBLE);
			findViewById(R.id.hot_word_title_refresh).setOnClickListener(this);
			if (mWords.size() <= 12) {
				findViewById(R.id.hot_word_title_refresh).setVisibility(View.GONE);
			} else {
				findViewById(R.id.hot_word_title_refresh).setVisibility(View.VISIBLE);
			}
			List<String> randomWords = getRandomHotWords(mWords, 12);
			for (String word : randomWords) {
				HotWordsUICard card = new HotWordsUICard(this, word);
				card.setTitle(word);
				card.setOnClickListener(this);
				mCardsArray.add(card);
			}
			mCardAdapter.notifyDataSetChanged();
		}

	}

	@Override
	public void onTaskRunError(int tag) {

	}

	@Override
	public void onTaskRunCanceled(int tag) {

	}

	@Override
	public void onClick(Card card, View view) {
		startSearch(card.getTitle());
	}

	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		if (actionId == EditorInfo.IME_ACTION_SEARCH) {
			startSearch(mSearchEt.getText().toString().trim());
			return true;
		}
		return false;
	}

	private void startSearch(String key) {
		if (TextUtils.isEmpty(key)) {
			Toast.makeText(this, R.string.please_input_search_keyword, Toast.LENGTH_SHORT).show();
			return;
		}
		myUmengStaticstics.onSearch(getApplicationContext());
		Intent intent = new Intent(this, SearchResultActivity.class);
		intent.putExtra(SearchResultActivity.EXTRA_KEY, key);
		startActivity(intent);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.search_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;
		case R.id.action_search_management:
			startSearch(mSearchEt.getText().toString().trim());
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.back_bn:
			goBack();
			break;
		case R.id.clear_edit_view:
			mSearchEt.setText("");
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.showSoftInput(mSearchEt, InputMethodManager.HIDE_IMPLICIT_ONLY);
			break;
		case R.id.hot_word_title_refresh:
			refreshHotWords();
			break;
		default:
			break;
		}
	}

	private void refreshHotWords() {
		mCardsArray.clear();
		List<String> randomWords = getRandomHotWords(mWords, 12);
		for (String word : randomWords) {
			HotWordsUICard card = new HotWordsUICard(this, word);
			card.setTitle(word);
			card.setOnClickListener(this);
			mCardsArray.add(card);
		}
		mCardAdapter.notifyDataSetChanged();
	}

	private List<String> getRandomHotWords(List<String> wordList, int num) {
		if (wordList == null || num < 0 || wordList.size() <= num) {
			return wordList;
		}

		int size = wordList.size();
		boolean flag[] = new boolean[size];
		List<String> randomList = new ArrayList<String>();
		int n = 0;
		Random random = new Random();
		while (true) {
			int temp = random.nextInt(size);
			if (!flag[temp]) {
				if (n == num)
					break;
				flag[temp] = true;
				randomList.add(wordList.get(temp));
				n++;
			}
		}
		return randomList;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			goBack();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void goBack() {
		AppMarketApplication app = (AppMarketApplication) getApplication();
		if (app.isAppRunning()) {
			Intent intent = new Intent(Intent.ACTION_MAIN);
			intent.addCategory(Intent.CATEGORY_LAUNCHER);
			intent.setClass(this, MainActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
			startActivity(intent);
		} else {
			Intent intent = new Intent(this, MainActivity.class);
			startActivity(intent);
		}
		finish();
	}

	@Override
	public void onRecommandFinished(CardApkRecommend recommend) {
		if (recommend == null || mDestroyed) {
			return;
		}

		CardView recommendView = findViewById(R.id.search_recommend_card);
		recommendView.setVisibility(View.VISIBLE);
		recommend.setTitle("大家还搜索了");
		ApkRecommendUICard recommendCard = new ApkRecommendUICard(SearchActivity.this, recommend);
		recommendCard.setApkSource(new ApkSource("recommend", null, null, "search"));
		recommendView.setCard(recommendCard);
		addFileListener(recommendCard);
	}
}
